// 
// Entify project
//  
// Author:
//       Lauri Taimila <lauri@taimila.com>
// 
// Copyright (c) 2010 Lauri Taimila
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;

namespace MonoDevelop.EntifyEditor
{
	/// <summary>
	/// Widget for editing property details.
	/// </summary>
	public partial class PropertyDetailsWidget : Gtk.Bin
	{
		/// <summary>
		/// Event indicates that property details has been changed from the editor.
		/// </summary>
		public delegate void PropertyDetailsChanged();
    	public event PropertyDetailsChanged DetailsChanged;

		/// <summary>
		/// Property which details are modified with this widget.
		/// </summary>
		private Property model;

		/// <summary>
		/// Sets property model to view and updates view
		/// to represent the current model.
		/// </summary>
		public Property Model
		{
			set
			{
				this.model = value;
				this.UpdateView();
			}
		}

		/// <summary>
		/// Creates a new property details widget.
		/// </summary>
		public PropertyDetailsWidget()
		{
			this.Build();
			this.model = null;
			this.UpdateView();
		}

		public void FocusToPropertyNameEntry()
		{
			this.PropertyDetailsNotebook.CurrentPage = 0;
			this.PropertyNameEntry.HasFocus = true;
		}

		/// <summary>
		/// Updates UI components to represent values of the current model.
		/// </summary>
		private void UpdateView()
		{
			if(this.model == null)
			{
				this.PropertyNameEntry.Text = "";
				this.PropertyDescriptionEntry.Text = "";
				this.PropertyTypeEntry.Active = 0;
				this.PropertyDetailsNotebook.Page = 0;
				this.PropertyDetailsNotebook.Sensitive = false;
			}
			else
			{
				// Set property type. Add type to list if it doesn't contain it already
				if(this.model.Type == null)
				{
					this.PropertyTypeEntry.Active = 0;
				}
				else
				{
					string typeName = this.model.Type;

					if(this.TypeComboboxContains(typeName))
					{
						this.PropertyTypeEntry.Active = this.GetComboboxPosition(typeName);
					}
					else
					{
						Console.WriteLine(typeName);
						this.PropertyTypeEntry.InsertText(0, typeName);
						this.PropertyTypeEntry.Active = 0;
					}
				}

				this.IndexCheckbutton.Active = this.model.Index;
				this.UniqueCheckbutton.Active = this.model.Unique;
				this.PropertyNameEntry.Text = this.model.Name;
				this.PropertyDescriptionEntry.Text = this.model.Description;
				this.UpdateValidatorTab();
				this.PropertyDetailsNotebook.Sensitive = true;
			}
		}
		
		/// <summary>
		/// Update validator tab to reflect current type of the property.
		/// </summary>
		private void UpdateValidatorTab()
		{
			// Remove existing validator tab
			try
			{
				this.ValidationTabContainer.Remove(this.ValidationTabContainer.Children[0]);
			}
			catch {}

			if(this.model.Type == typeof(string).FullName)
			{
				ValidationTabForStringWidget validationTab = new ValidationTabForStringWidget(this.model);
				validationTab.Visible = true;
				this.ValidationTabContainer.Add(validationTab);
			}
			else if(this.model.Type == typeof(Int16).FullName ||
			        this.model.Type == typeof(UInt16).FullName ||
			        this.model.Type == typeof(Int32).FullName ||
			        this.model.Type == typeof(UInt32).FullName ||
			        this.model.Type == typeof(Int64).FullName ||
			        this.model.Type == typeof(float).FullName ||
			        this.model.Type == typeof(double).FullName ||
			        this.model.Type == typeof(decimal).FullName)
			{
				ValidationTabForNumericWidget validationTab = new ValidationTabForNumericWidget(this.model);
				validationTab.Visible = true;
				this.ValidationTabContainer.Add(validationTab);
			}
			else if(this.model.Type == typeof(DateTime).FullName)
			{
				ValidationTabForDateTimeWidget validationTab = new ValidationTabForDateTimeWidget(this.model);
				validationTab.Visible = true;
				this.ValidationTabContainer.Add(validationTab);
			}
			//FIXME: Is it possible to detect is type enum or serializable when it's not in the type system
			/*
			else if(!this.model.Type.IsEnum && this.model.Type.IsSerializable)
			{
				ValidationTabForSerializableWidget validationTab = new ValidationTabForSerializableWidget(this.model);
				validationTab.Visible = true;
				this.ValidationTabContainer.Add(validationTab);
			}
			*/
			else
			{
				Gtk.Label label = new Gtk.Label("No validation settings for\ncurrent property type.");
				label.Visible = true;
				this.ValidationTabContainer.Add(label);
			}
		}

		/// <summary>
		/// Called when property name has been changed. Updates the model.
		/// </summary>
		protected virtual void OnPropertyNameEntryChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Name = this.PropertyNameEntry.Text.Trim();
				this.model.PersistentName = this.model.Name;
				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Called when property description has been changed. Updates the model.
		/// </summary>
		protected virtual void OnPropertyDescriptionEntryChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Description = this.PropertyDescriptionEntry.Text.Trim();
				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Called when property type has been changed. Updates the model.
		/// </summary>
		protected virtual void OnPropertyTypeEntryChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				string type = this.PropertyTypeEntry.ActiveText.Trim();
	
				if(string.IsNullOrEmpty(type))
				{
					//TODO: What should we do if user gives empty string?
				}
				else
				{
					//TODO: Reset style
					this.model.Type = type;
					this.UpdateValidatorTab();
				}

				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Probably the most ugliest way to find out if combobox contains a string.
		/// </summary>
		private bool TypeComboboxContains(string type)
		{
			//FIXME: How this should be done with GTK?
			string lastSeenType = "";
			int counter = 0;

			while(true)
			{
				this.PropertyTypeEntry.Active = counter;

				if(lastSeenType == this.PropertyTypeEntry.ActiveText)
				{
					return false;
				}

				if(type.Equals(this.PropertyTypeEntry.ActiveText))
				{
					return true;
				}

				lastSeenType = this.PropertyTypeEntry.ActiveText;
				counter++;
			}
		}

		/// <summary>
		/// Dangerous and ugly way to find position index for
		/// given string in property type combobox.
		/// </summary>
		private int GetComboboxPosition(string type)
		{
			//FIXME: How this should be done with GTK?
			int counter = 0;

			while(true)
			{
				this.PropertyTypeEntry.Active = counter;
				if(type.Equals(this.PropertyTypeEntry.ActiveText))
				{
					return counter;
				}

				counter++;
			}
		}
		protected virtual void OnIndexCheckbuttonToggled (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Index = this.IndexCheckbutton.Active;
				this.DetailsChanged();
			}
		}
		
		protected virtual void OnUniqueCheckbuttonToggled (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Unique = this.UniqueCheckbutton.Active;
				this.DetailsChanged();
			}
		}
	}
}
